package coderun

//Purpose：生成执行文件（暂仅py）

import (
	"bufio"
	"fmt"
	"os"
	"strings"

	"github.com/google/uuid"
)

var fileroot string = "excefileroot/"

func getTemplate() string {
	file, err := os.Open("coderun/pymain")
	if err != nil {
		fmt.Println("Open coderun/pymain ", err)
		panic(err)
	}
	defer file.Close()
	r := bufio.NewReader(file)

	buf := make([]byte, 128)
	r.Read(buf)

	return string(buf)
}

func RunCode(code string, ptitle string) float32 {

	mainTemplate := getTemplate()
	testCases := pyMakeMains(ptitle)
	total := 0
	rightNum := 0
	for key, value := range testCases {
		randomSeed := uuid.New().String()
		filename := fileroot + randomSeed + ".py"
		fn, _ := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0777)
		defer fn.Close()

		total += 1
		fn.Seek(0, 0)
		_, err := fn.Write([]byte(code + strings.ReplaceAll(mainTemplate, "*theArgs", key)))
		if err != nil {
			fmt.Println(err)
			return 0.0
		}
		args := make([]string, 0)
		args = append(args, filename)
		result := Runpy(args)
		if Judge(result, value) == true {
			rightNum += 1
		}
	}
	return float32(rightNum) / float32(total) * float32(100)
}
